#include "util.h"

#include <string.h>
#include <windows.h>

char* util::wcsToAnsi( const wchar_t *s )
{
	//Convert a wide character string to an ANSI string (1 byte per character).
	//The returned value should be freed using delete[].
	char *mbs;

	//Calculate the length of the output buffer.
	size_t mbsLength = wcslen( s );

	//Allocate the output buffer.
	mbs = new char[ mbsLength+1 ];
	memset( mbs, '\0', mbsLength+1 );

	//Convert the string.
	WideCharToMultiByte( CP_ACP, 0, s, -1, mbs, mbsLength, NULL, NULL );
	return mbs;
}

char* util::wcsToUtf8( const wchar_t *s )
{
	//Convert a wide character string to an UTF-8 multibyte string.
	//The returned value should be freed using delete[].
	char *mbs;

	//Calculate the length of the output buffer.
	int mbsLength = WideCharToMultiByte( CP_UTF8, 0, s, -1, NULL, 0, NULL, NULL );
	if( mbsLength == 0 )
		return NULL;

	//Allocate the output buffer.
	mbs = new char[ mbsLength ];
	memset( mbs, '\0', mbsLength );

	//Convert the string.
	WideCharToMultiByte( CP_UTF8, 0, s, -1, mbs, mbsLength, NULL, NULL );
	return mbs;
}

wchar_t* util::utf8ToWcs( const char *s )
{
	//Convert an UTF-8 multibyte string to a wide character string.
	//The returned value should be freed using delete[].
	wchar_t *wcs;

	//Calculate the length of the output buffer.
	int wcsLength = MultiByteToWideChar( CP_UTF8, 0, s, -1, NULL, NULL );
	if( wcsLength == 0 )
		return NULL;

	//Allocate the output buffer.
	wcs = new wchar_t[ wcsLength ];
	memset( wcs, '\0', wcsLength );

	//Convert the string.
	MultiByteToWideChar( CP_UTF8, 0, s, -1, wcs, wcsLength );
	return wcs;
}
